package cn.zwt.wolf.service.sync;

import cn.zwt.wolf.domain.sync.SyncQueue;
import cn.zwt.wolf.repository.dataSync.SyncQueueRepository;
import cn.zwt.wolf.util.JPQLSearchException;
import cn.zwt.wolf.util.SearchUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.NoResultException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangwt on 16-3-4.
 */
@Service
public class SyncQueueService {
    @Autowired
    private SyncQueueRepository syncQueueRepository;
    @Autowired
    private SearchUtil searchUtil;
    private Log logger = LogFactory.getLog(SyncQueueService.class);

    public void savaOrUpdate(SyncQueue syncQueue){
        if (syncQueue!=null)
            syncQueueRepository.save(syncQueue);
    }
    public SyncQueue findSyncQueueById(int id){
        return syncQueueRepository.findOne(id);
    }
    public SyncQueue findSyncQueueByContentId(int contentId) {
        SyncQueue syncQueue = null;
        if ((Integer)contentId == null){
            return syncQueue;
        }
        String hql = "from SyncQueue where contentId=:contentId";
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("contentId", contentId);
        try {
            syncQueue = (SyncQueue) searchUtil.getSingleResult(hql,map);
        } catch (JPQLSearchException e) {
            logger.error("find SyncQueuesByContentId error :" + e.getMessage());
        }catch (NoResultException e){
            logger.error("find SyncQueuesByContentId error :" + e.getMessage());
        }
        return  syncQueue;
    }
    public List<SyncQueue> findSyncQueuesByStatus(Map<String,Object> params){
        List<SyncQueue> syncQueues = null;
        if (params.size()==0)
            return syncQueues;
//        String hql = "from SyncQueue where status=:status and collectStatus=:collectStatus" +
//                " and enterStatus=:enterStatus and publishStatus=:publishStatus";
        String hql = "from SyncQueue ";
        if (params.get("status")!=null)
            hql += " where status=:status ";
        else
            hql += " where status = 1 ";
        if (params.get("collectStatus")!=null)
            hql += " and collectStatus =:collectStatus ";
        if (params.get("enterStatus")!=null)
            hql += " and enterStatus =:enterStatus ";
        if (params.get("publishStatus")!=null)
            hql += " and publishStatus =:publishStatus ";
        try {
            syncQueues =  searchUtil.getResultList(hql, params);
        } catch (JPQLSearchException e) {
            logger.error("find findSyncQueuesByStatus error :" + e.getMessage());
        }catch (NoResultException e){
            logger.error("find findSyncQueuesByStatus error :" + e.getMessage());
        }
        return  syncQueues;
    }
}
